# -*- coding:utf-8 -*- 
# @Time : 2021/1/25 9:41
# @Author: sl
# @File : XxlJobRunSiteQc.py
import json
import logging
import traceback
from importlib import import_module
from flask import request
from flask_restful import Resource
from threading import Thread
import subprocess
import time
import requests
from framework import app
from framework.util.ComplexEncoder import ComplexEncoder


class StartXxlJob(Resource):
    def post(self):
        request_data = request.get_json()
        if "BEAN" in request_data["glueType"]:
            logging.info("bean模式，执行对应方法")
            t = Thread(target=deal, args=(request_data["executorHandler"], request_data["logId"]))
            t.start()
        else:
            logging.info("GLUE(Shell)模式，执行脚本，为了原来crontab使用的程序")
            t = Thread(target=cron_func, args=(request_data["glueSource"], request_data["logId"]))
            t.start()
        return {"code": 200, "msg": None}


def deal(executor_handler, log_id):
    mod = import_module("job.handler.{}".format(executor_handler))
    instance = getattr(mod, executor_handler)()
    code = 200
    try:
        log_msg = instance.run()
        log_msg=json.dumps(log_msg, cls=ComplexEncoder)
    except Exception as e:
        logging.error("xxljob任务异常", exc_info=True)
        code = 500
        log_msg = traceback.format_exc()
    request_msg = [{
        "logId": log_id,
        "logDateTim": int(time.time()),
        "handleCode": code,
        "handleMsg": log_msg
    }]

    requests.post(app.config["XXLJOB_CALLBACK_URL"], json=request_msg)


def cron_func(glue_source, log_id):
    completed_obj = subprocess.run(glue_source, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    return_code = completed_obj.returncode
    code = 200 if return_code == 0 else 500
    log_msg = completed_obj.stdout.decode("utf-8")
    request_msg = [{
        "logId": log_id,
        "logDateTim": int(time.time()),
        "handleCode": code,
        "handleMsg": log_msg
    }]
    requests.post(app.config["XXLJOB_CALLBACK_URL"], json=request_msg)





# def thread_start(logId=0):
#     time.sleep(10)
#     url = "http://127.0.0.1:8080/xxl-job-admin/api/callback"
#     datas = list()
#     data = {
#         "logId": logId,
#         "logDateTim": 0,
#         "handleCode": 200,
#         "handleMsg": "执行完毕sl"
#         # "executeResult": {
#         #     "code": 200,
#         #     "msg": "执行完毕sl"
#         # }
#     }
#     datas.append(data)
#
#     # 定制请求头
#     # header 指定请求头为json格式
#     headers = {'Content-Type': 'application/json'}
#     # 方法1 data 传参，通过json.dumps 转化为json格式
#     r = requests.post(url=url, headers=headers, data=json.dumps(datas))
#     print(r.status_code)
#
#
# class XxlJobSample(AbstractApi):
#     def handle_post_request(self):
#         logging.info("调度起{}".format(request.get_json()))
#         json1 = request.get_json()
#         logging.info("logId{}".format(json1["logId"]))
#         # mythread = threading.Thread(target=thread_start, args=(json1["logId"],))
#         # mythread.start()
#         # time.sleep(10)
#         return RespResult(RespCode.XXL_JOB_OK, "返回ip")
